

package top.continew.admin.question.manger.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import top.continew.admin.question.model.area.Area;
import top.continew.admin.question.manger.service.AreaService;
import top.continew.admin.question.manger.service.model.AreaVO;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class AreaServiceImpl implements AreaService {
    @Override
    public List<AreaVO> getArea() {
        List<Area> province = new Area().selectList(new QueryWrapper<Area>().eq("level", 1));
        List<Area> city = new Area().selectList(new QueryWrapper<Area>().eq("level", 2));
        Map<Long, List<Area>> mapCity = city.stream().collect(Collectors.groupingBy(Area::getParentId));
        List<Area> region = new Area().selectList(new QueryWrapper<Area>().eq("level", 3));
        Map<Long, List<Area>> mapRegion = region.stream().collect(Collectors.groupingBy(Area::getParentId));
        return province.stream().map(pro -> {
            AreaVO area = new AreaVO();
            area.setLabel(pro.getName());
            area.setValue(pro.getId());
            area.setChildren(mapCity.getOrDefault(pro.getId(), new ArrayList<>()).stream().map(ci -> {
                AreaVO cityVO = new AreaVO();
                cityVO.setValue(ci.getId());
                cityVO.setLabel(ci.getName());
                cityVO.setChildren(mapRegion.getOrDefault(ci.getId(), new ArrayList<>()).stream().map(re -> {
                    AreaVO regionVO = new AreaVO();
                    regionVO.setValue(re.getId());
                    regionVO.setLabel(re.getName());
                    return regionVO;
                }).collect(Collectors.toList()));
                return cityVO;
            }).collect(Collectors.toList()));
            return area;
        }).collect(Collectors.toList());
    }
}
